package nautilus.utility;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

import android.util.Log;

public class SocketIOService extends Thread {

	private static String TAG = "SocketIOService";
	private Socket socket;
	private volatile boolean isRunning = false;
	private byte[] buffer = new byte[1024];
	private ByteQueue byteQueue;
	private OutputStream outStream;
	
	private static final byte[] CLOSECMD = {(byte)0xFE, (byte)0xFE, (byte)0xFF, (byte)0xFE, (byte)0xFF};
	
	public SocketIOService(String serverHost, int port){
		try {
			socket = new Socket(serverHost, port);
			byteQueue = new ByteQueue(1024);
			isRunning = true;
			outStream = socket.getOutputStream();
		} catch (UnknownHostException e) {
			Log.e(TAG, e.getMessage());
		} catch (IOException e1) {
			Log.e(TAG, e1.getMessage());
		}
	}
	
	public void sendData(byte[] data){
		try{
			outStream.write(data);
			outStream.flush();
		}catch(IOException e1){
			Log.e(TAG, e1.getMessage());
		}
	}
	
	public void closeSocket(){
		try{
			isRunning = false;
			socket.close();
		}catch(IOException e1){
			Log.e(TAG, e1.getMessage());
		}
	}
	
	@Override
	public void run(){
		InputStream inStream = null;
		try{
			inStream = socket.getInputStream();
			int i, byteRead = 0;
			while(isRunning){
				if( (byteRead = inStream.read(buffer, 0, 1024)) > 0 ){
					byteQueue.add(buffer, byteRead);
					
					for(i=0; byteRead>4 && i<byteRead-4; i++){
						if(buffer[i]==CLOSECMD[0] &&
								buffer[i+1]==CLOSECMD[1] &&
								buffer[i+2]==CLOSECMD[2] &&
								buffer[i+3]==CLOSECMD[3] &&
								buffer[i+4]==CLOSECMD[4]){
							isRunning = false;
							break;
						}
					}
				}
			}		
		}catch(IOException e1){
			//Actually we don't need to do anything here	
		}catch(InterruptedException e2){
			Log.e(TAG, e2.getMessage());
		}
	}
}
